// pages/bucketAnalyse/bucketAnalyse.js
import * as ec from "./echarts.min"
import { shareOptions } from "../../utils/access";
import { getBarAndTitleHeight, jump, paramSplicing, setStorage, parse, getScreenSize} from "../../utils/utils";
import api from "../../config/api";
import request from "../../utils/request";

const comp = requirePlugin('echarts');
comp.echarts = ec;

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 判断显示内容
    type:'2',
    // 垃圾桶类型数组
    typeTextData:['非垃圾桶','厨余垃圾桶','其他垃圾桶','混合垃圾桶','空垃圾桶'],
    // 控制盒子高度变化的变量
    viewHeight:['400','1000'],
    viewHeightItem: 1,
    // 外层图片的高度
    animation:null,
    // 上层饼图的数据
    ec:{
      color:[
        '#5470C6',
        '#92CB74',
        '#FAC858',
        '#EF6565',
        '#73C0DD',
        '#5654F3',
        '#5632A5',
        '#FF7474',
        '#6FD7F2',
        '#F3D02F',
        '#EB2BCB',
        '#00C8A1',
        '#6AC963',
      ],
      series: {
              name: '访问来源',
              type: 'pie',
              radius: ['45%', '72%'],
              avoidLabelOverlap: false,
              clockwise:false,
              // roseType: 'radius',
              // startAngle: 90,
              label: {
                  show: false,
                  position: 'center'
              },
              emphasis: {
                  label: {
                      show: true,
                      fontSize: '18',
                      fontWeight: 'bold'
                  }
              },
              labelLine: {
                  show: false
              },
              data: [
              ]
          }
    },
    // 分析成分数组
    recognitionData:[
    ],
    // 分析成份数组颜色
    recognitionColorData:{
        0:'#5470C6',
        1:'#92CB74',
        2:'#FAC858',
        3:'#EF6565',
        4:'#73C0DD',
        5:'#5654F3',
        6:'#5632A5',
        7:'#FF7474',
        8:'#6FD7F2',
        9:'#F3D02F',
        10:'#EB2BCB',
        11:'#00C8A1',
        12:'#6AC963',
    },
    // 拍照图片
    url:'',
    // 识别的数据
    ingredient:[],
    // 饼图使用的数据
    areaData:[],
    // 垃圾桶分类
    classifyData:[
      '你拍到的不是垃圾桶！',
      '桶内厨余垃圾超过80%',
      '桶内其他垃圾比例超过80%',
      '桶内垃圾混合比例超过20%',
      '垃圾桶内物品不足5%',
    ],
    hintData:[
      '小K识别到，您拍的并不是垃圾桶。您可以对准垃圾桶内部重新拍照。',
      '主要用于盛放厨余垃圾的垃圾桶。在家中通常可以摆放在厨房中，便于投放。',
      '主要用于盛放其他垃圾的垃圾桶。家中客厅、卧室、卫生间均可摆放。',
      '还在混合投放垃圾？至少要将“厨余垃圾桶”和“其他垃圾桶”分开使用啊。',
      '居家生活离不开。在家中至少要将“厨余垃圾桶”和“其他垃圾桶”分开使用。'
    ],
    // 传递给纠错页面的参数
    taskData:{},
    // 初始滑动位置
    scrollY: 0,
    // 状态栏&标题栏高度
    ...getBarAndTitleHeight(),
    // 物品图片地址
    thingUrl: null,
    // 图片放大比例
    picScale: 1,
    // AI图片地址
    aiUrl: null,
    // 是否是测试环境
    isDev: false,
    // 垃圾数组
    pointList:[],
    // 屏幕宽度
    screenWidth: 375,
    // 滑动到某个垃圾id
    scrollIntoId: '',
    // 上滑盒子高度
    contentHeight: 0,
    // 选中标签id
    selectedId: '',
    safeBottom: 0
  },
  loading: false,
  // 画线定时
  interval: null,
  interval1: null,
  // 1, 盒子高度动态变化
  // 1.1, 上箭头--盒子变大
  bigBtn() {
    const { viewHeightItem } = this.data
    this.animation.height('88%').step()
    this.setData({
      viewHeightItem: viewHeightItem === 1 ? 2 : 1,
      animation: this.animation.export(),
    })
    this.clearCanvas()
  },
  // 1.2 下箭头--盒子变小
  smallBtn(type){
    const { contentHeight, viewHeightItem } = this.data
    this.animation.height(contentHeight).step()
    this.setData({
      viewHeightItem: viewHeightItem === 1 ? 2 : 1,
      animation: this.animation.export(),
    })
  },
  // 滑动开始
  scrollTouchStart(event) {
    this.setData({
      scrollY: event?.touches?.[0]?.pageY || 0
    })
  },
  // 滑动移动
  scrollTouchMove(event) {
    const { scrollY, type } = this.data
    if (!['1', '2', '3'].includes(type)) return
    const currentX = event?.touches?.[0]?.pageY || 0

    if (currentX <= scrollY) {
      console.log('上滑')
      this.touchType = 'up'
    } else {
      console.log('下滑')
      this.touchType = 'down'
    }
  },
  // 滑动结束
  scrollTouchEnd(event) {
    const { viewHeightItem } = this.data

    if (this.touchType === 'up') {
      console.log('上滑')
      if (viewHeightItem === 1) {
        this.bigBtn()
      }
    }
    if (this.touchType === 'down') {
      console.log('下滑')
      if (viewHeightItem === 2) {
        // this.smallBtn(viewHeightItem === 2 ? 1 : 2)
        this.smallBtn()
      }
      
    }
    this.touchType = null
  },
  // 放大变化
  sliderchange(e) {
    this.setData({
      picScale: (e?.detail?.value / 100 + 1) || 1
    })
  },
  // 改变物品地址
  changeThingUrl(e) {
    this.setData({
      thingUrl: e.currentTarget.dataset.url
    })
  },
  // 用于ai测试
  async showAiPic() {
    const { url, aiUrl } = this.data
    // ai测试
    if (aiUrl) {
      wx.previewImage({
        urls: [aiUrl, url].filter(Boolean),
      })
    } else {
      wx.showLoading({
        title: '加载中',
      })
      wx.request({
        method: 'POST',
        url: 'http://192.168.11.181:9800/api/inference/v2/n/hot/or/waste/',
        data: {
          url,
          is_dd_test: 1,
        },
        success: (result) => {
          console.log('ai测试：', result)
          const res = result?.data || {}
          wx.hideLoading()
          if (res?.code === 200) {
            this.setData({
              aiUrl: res?.data
            })
            wx.previewImage({
              urls: [res?.data, url].filter(Boolean),
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: res?.msg || '请求失败',
            })
          }
        },
        fail: (err) => {
          console.log('ai测试：', err)
          wx.showToast({
            icon: 'none',
            title: '请求失败',
          })
        }
      })
    }
  },
  // 2.0 处理识别信息
  getRecognitionData(){
    const {recognitionData,recognitionColorData, ingredient, ec } = this.data
    const a = ingredient?.mixProportion
    console.log(a,'等待循环的数组')
    const list = a?.map((item,index)=>{
      return {...item,color:recognitionColorData[index]}
    })
    const newList = list?.map((item,index)=>{
      return {...item,value:item.proportion.replace('%','')}
    })
    console.log(a)
    console.log(newList,'处理后的数据')
    // 2.1 处理饼图可用的数据
    let newData = []
    newData = ingredient?.mixProportion?.map((item=>{
      return {
        value:item.proportion.replace('%',''),
        name:item.garbageName || item.garbageTypeName,
      }
    }))
    console.log(newData,'饼图使用的数据')
    // 2.2 处理垃圾分类数据
    ec.series.data = newData
    // 统计数量
    this.setData({
      recognitionData:newList,
      ec,
      areaData:newData
    })
  },
  // 3.0 跳转我要纠错页面
  goBucketError(){
    this.clearCanvas()
    if (!app.isLogin()) {
      this.toLogin()
      return
    }
    const { ingredient, ...params } = this.data?.taskData || {}
    jump('bucketAnalyseCorrection', params)
  },
  // 去登陆
  toLogin() {
    setStorage('redirectPath', '/pages/bucketAnalyse/bucketAnalyse')
    setStorage('redirectParams', paramSplicing('', this.options))
    app.login()
  },
  // 判断提示文案
  getMsgContent: async function(){
    const res = await request.get(`${api.query25DaysTask}`)
      if(res.httpStatus===200){
        let {durationDays, remainDays } = res.data
        let taskDone = durationDays === 7 || durationDays === 14 || (durationDays !== 0 && durationDays % 25 ===0);
        if(taskDone){
          setTimeout(() => {
            wx.showToast({
              icon: 'none',
              title: '任务完成，请在我的-兑换券中查看奖品',
              duration: 2000
            })
          }, 300)
        }else{
          setTimeout(() => {
            wx.showToast({
              icon: 'none',
              title: `任务完成，距离奖品券还有${remainDays}天`,
              duration: 2000
            })
          }, 300)
        }
      }
  },
  /**
   * 生命周期函数--监听页面加载 options
   */
  onLoad: function (options) {
    this.options = options
    if (options.showMsg) {
      // setTimeout(() => {
      //   wx.showToast({
      //     icon: 'none',
      //     title: '今日任务已完成',
      //     duration: 2000
      //   })
      // }, 300)
      this.getMsgContent()
    }
    let ingredientList =  parse(options.ingredient)
    let centerList = []

    // 系统信息
    const systemInfo = wx.getSystemInfoSync()
    // px转换到rpx的比例
    const pxToRpxScale = 750 / systemInfo.windowWidth

    ingredientList?.garbageProportion?.forEach((item,index)=>{
        let obj = {
          id: index,
          name: item.garbageName,
          isError: item.garbageCorrection
        }
        let pointArr = item.centralPoint.split(',')
        obj.top = +(pointArr[1]) * pxToRpxScale - 28   
        obj.left = +(pointArr[0]) * pxToRpxScale - 28
        centerList.push(obj)
    })

    const ingredient = ingredientList // parse(options.ingredient)
    // 计算物品列表宽度
    const thingsWidth = ingredient?.garbageList instanceof Array
      ? ingredient?.garbageList?.reduce((t, c) => {
        const len = c.name.split('').reduce((num, str) => {
          return num + (str.charCodeAt(0) > 255 ? 1 : 0.5)
        }, 0)
        return t + (len - 2) * 28 + 160
      }, 0)
      : 750
    console.log(options.hasOwnProperty('taskData'))
    this.setData({
      taskData:(options.hasOwnProperty('taskData')) ? parse(options.taskData):options,
      type: options.bucketType,
      url: options.url,
      ingredient,
      thingsWidth,
      isDev: !api.authSwap.startsWith('https'),
      pointList: centerList
    })
    
    console.log(this.data.taskData)
    console.log(this.data.ingredient)

    if(options.bucketType === '1' || options.bucketType === '2' || options.bucketType === '3'){
      this.init()
    }

    // 适配iPhoneX系列--底部弹窗距离
    wx.getSystemInfo({
      success: (res) => {
        let safeBottom = res.screenHeight - res.safeArea.bottom
        this.setData({
          safeBottom,
        })
      },
    })

    let { screenWidth, screenHeight } = getScreenSize()
    this.setData({
      screenWidth: screenWidth,
      contentHeight: screenHeight - screenWidth - 70
    })
  },
  // 初始化canvas
  init(){
    if (this.inited) {
      return
    }
    const query = this.createSelectorQuery()
    query.select('#lineCanvas')
    .fields({ node: true, size: true })
    .exec((res) => {
      const canvas = res[0].node
      const ctx = canvas.getContext('2d')
      const dpr = wx.getSystemInfoSync().pixelRatio
      canvas.width =  res[0].width * dpr
      canvas.height = res[0].height * dpr
      ctx.scale(dpr, dpr)
      this.canvas = canvas
      this.ctx = ctx
      this.inited = true

      if(this.data.pointList.length > 0){
        let { id, isError } = this.data.pointList[0]
        let e = {
          currentTarget : {
            dataset: {
              item:{
                id: id,
                isError: isError
              }
            }
          }
        }
        this.setData({
          selectedId: id
        })
        this.jumpThing(e)
      }
    })
  },  
  // 点击动态点
  jumpPoint(e){
    let that = this
    if(that.loading){
      return
    }
    that.loading = true
    const { contentHeight } = this.data
    this.animation.height(contentHeight).step()
    this.setData({
      viewHeightItem: 1,
      animation: this.animation.export(),
    })
    this.clearCanvas()
    let { id, isError } = e.currentTarget.dataset.item
    let currentX,  // 当前点击点X坐标
        currentY, // 当前点击点Y坐标
        lineEndX, lineEndY // 名称所在X，Y坐标

    let color = isError=== 1 ? '#EE605B' : '#fff' // 连接线颜色

    this.setData({
      scrollIntoId: `thingItem${id}`,
      selectedId: id
    })

    wx.createSelectorQuery().in(this).select(`#pointItem${id}`).boundingClientRect((res) => {
      currentX = res.left + res.width/2
      currentY = res.top + res.width/2
    }).exec()

    setTimeout(()=>{
      wx.createSelectorQuery().in(this).select(`#thingItem${id}`).boundingClientRect((res) => {
        lineEndX = res.left + res.width/2
        lineEndY = res.top
        // this.interval = null; //计时器对象
        // this.interval1 = null; //计时器对象
        this.drawPointLine(currentX,currentY,lineEndX,lineEndY,color)
      }).exec()
    },500)
  },
  // 点击标签
  jumpThing(e){
    let that = this
    if(that.loading){
      return
    }
    that.loading = true
    const { contentHeight } = this.data
    this.animation.height(contentHeight).step()
    this.setData({
      viewHeightItem: 1,
      animation: this.animation.export(),
    })
    this.clearCanvas()
    let { id, isError } = e.currentTarget.dataset.item
    let currentX,  // 当前点击点X坐标
        currentY, // 当前点击点Y坐标
        lineEndX, lineEndY // 名称所在X，Y坐标

    let color = isError=== 1 ? '#EE605B' : '#fff' // 连接线颜色

    this.setData({
      scrollIntoId: `thingItem${id}`,
      selectedId: id
    })

    setTimeout(()=>{
      wx.createSelectorQuery().in(this).select(`#thingItem${id}`).boundingClientRect((res) => {
        currentX = res.left + res.width/2
        currentY = res.top
      }).exec()
      wx.createSelectorQuery().in(this).select(`#pointItem${id}`).boundingClientRect((res) => {
        lineEndX = res.left + res.width/2
        lineEndY = res.top + res.width/2
        // this.interval1 = null; //计时器对象
        this.drawThingLine(currentX,currentY,lineEndX,lineEndY,color)
      }).exec()
    },700)
  },
  // 滑动开始
  handleScrollStart(){
    this.clearCanvas()
  },
  // 清除画布
  clearCanvas(){
    console.log('clear interval 1[')
    // this.interval && clearInterval(this.interval)
    // this.interval1 && clearInterval(this.interval1)
    if(this.ctx){
      var w = this.canvas.width;
      var h = this.canvas.height;
      this.ctx.clearRect(0, 0, w, h);
      this.setData({
        selectedId: ''
      })
    }
  },
//点到标签动态画线
drawPointLine(startX,startY,lineEndX,lineEndY,color){
  let that = this
  let lengthX = lineEndX - startX
  let lengthY = lineEndY - startY
  let ctx = this.ctx
  var iLenX = 0;
  var iLenY = 0;
  ctx.beginPath();
  let radius = 6 // 半径
  let Yc = startY + radius
  clearInterval(this.interval)
  this.interval = null
  this.interval = setInterval(() => {
    if(iLenX<=(Math.abs(lengthX)-radius)){
      ctx.moveTo(startX,startY);
      if(lengthX > 0){
        startX = startX + 3
        ctx.lineTo(startX,startY);
      }else{
        startX = startX - 3
        ctx.lineTo(startX,startY);
      }
      ctx.lineWidth= 2.5;
      ctx.strokeStyle= color;

      iLenX = iLenX + 3;
      ctx.stroke();
      ctx.closePath();
    }else{
      clearInterval(this.interval)
      this.interval = null
      ctx.beginPath()

      if(lengthX > 0){
        ctx.arc(lineEndX-radius, startY+radius, radius, Math.PI * 1.5, Math.PI * 2)
        ctx.lineWidth= 2.5;
      }else{
        ctx.arc(lineEndX+radius, startY+radius, radius, Math.PI, Math.PI * 1.5)
        ctx.lineWidth= 2.5;
      }
      ctx.stroke()
      ctx.closePath();
      ctx.beginPath();
      // 画竖线
      const colDownLine = () => {
        if(iLenY<=(lengthY -radius)){
          ctx.moveTo(lineEndX,Yc);
          Yc = Yc + 2
          ctx.lineTo(lineEndX,Yc);
          ctx.lineWidth= 2.5;
          ctx.strokeStyle= color;
          iLenY = iLenY + 2;
          ctx.stroke();
          ctx.closePath();
        }else{
          clearInterval(this.interval)
          this.interval = null
          that.loading = false
        }
      }
      this.interval = setInterval(() => {
        colDownLine()
      },1)
    }
  },1);
},

// 标签到点动态画线
drawThingLine(startX,startY,lineEndX,lineEndY,color){
  let that = this
  let lengthX = lineEndX - startX
  let lengthY = lineEndY - startY
  let ctx = this.ctx
  var iLenX = 0;
  var iLenY = 0;
  let radius = 6 // 半径
  let Xc = startX - radius
  let Xc1 = startX + radius
  ctx.beginPath();
  let spead = 500/ (Math.abs(lengthX)+ Math.abs(lengthY))
  clearInterval(this.interval1)
  this.interval1 = null
  this.interval1 = setInterval(() => {
    // console.log(iLenY,Math.abs(lengthY) -radius)
    if(iLenY<=Math.abs(lengthY) -radius){
      ctx.moveTo(startX,startY+1);
      startY = startY - 2
      ctx.lineTo(startX,startY);
      ctx.lineWidth= 2.5;
      ctx.strokeStyle= color;
      iLenY = iLenY + 2
      ctx.stroke();
      ctx.closePath();
    }else{
      clearInterval(this.interval1)
      this.interval1 = null
      ctx.beginPath()
      if(lengthX < 0){
        ctx.arc(startX-radius, lineEndY+radius, radius, Math.PI * 1.5, Math.PI * 2)
        ctx.lineWidth= 2.5;
      }else{
        ctx.arc(startX+radius, lineEndY+radius, radius, Math.PI, Math.PI * 1.5)
        ctx.lineWidth= 2.5;
      }
      ctx.stroke()
      ctx.closePath();
      ctx.beginPath();
      // 画横线
      const rowDownLine = () => {
        if(iLenX<=(Math.abs(lengthX)-3 -radius)){
          if(lengthX > 0){
            ctx.moveTo(Xc1,lineEndY);
            Xc1 = Xc1 + 3
            ctx.lineTo(Xc1,lineEndY);
          }else{
            ctx.moveTo(startX - radius,lineEndY);
            Xc = Xc - 3
            ctx.lineTo(Xc,lineEndY);
          }
         
          ctx.lineWidth= 2.5;
          ctx.strokeStyle= color;
          iLenX = iLenX + 3
          ctx.stroke();
          ctx.closePath();
          
          
        }else{
          clearInterval(this.interval1)
          this.interval1 = null
          that.loading = false
        }
      }

      this.interval1 = setInterval(() => {
        rowDownLine()
      },1)
    }	
  },1);

},
  // 重新拍照
  handleRephoto(){
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 1.4 实例化一个动画
    this.animation = wx.createAnimation({
      // 动画持续时间
      duration:300,
      // 动画延迟时间
      delay: 100,
      timingFunction: 'ease',
      transformOrigin:'left top 0',
      success:function(res){
        console.log(res)
      }
    })
    this.getRecognitionData()
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
		return shareOptions('inviteWechatFriend', e)
	},
})